package com.termine.jsf;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.termine.bean.Bean;
import com.termine.entity.Location;
import com.termine.entity.PersonalData;

@ManagedBean
@SessionScoped
public class LoginJSF extends Bean implements Serializable {

	private static final long serialVersionUID = 7485188261726765110L;

	private PersonalData personalData;
	private Location location;
	private String email;
	private String password;
	private String whoAmI;	// 'ANONYM' or 'CLIENT' or 'PROVIDER'; is being set in MenuJSF on context switch

	/*
	 * Init
	 */
	@PostConstruct
	public void init() {
		whoAmI ="ANONYM";
		personalData = new PersonalData();
		location = new Location();
	}
	
	/*
	 * Jsf Action Methods
	 */
	public String performLogin() {
		try {
			personalData = getPersonalDataDAO().getPersonalData(email, password);
			if (personalData != null) {
				if (personalData.isProvider()) {
					whoAmI = "PROVIDER";
				}
				if (personalData.isClient()) {
					whoAmI = "CLIENT";
				}
				location = getLocationDAO().getLocation(personalData);
				email = "";
				password = "";
				setInfoMessage("hi " + getLoginJSF().getPersonalData().getForename());
				return whoAmI;
			}
			else {
				email = "";
				password = "";
				setErrorMessage("login failed");
				return "ERROR";		
			}
		} catch (Exception e) {
			e.printStackTrace();
			setFatalMesssage(e.getMessage());
			return "ERROR";
		}	
	}
	
	public String performLogout() {
		init();
		setInfoMessage("logged out");
		return "SUCCESS";
	}
	
	/*
	 * Getters & Setters
	 */
	
	public String getEmail() {
		return email;
	}

	public Location getLocation() {
		return location;
	}

	public void setLocation(Location location) {
		this.location = location;
	}

	public String getWhoAmI() {
		return whoAmI;
	}

	public void setWhoAmI(String whoAmI) {
		this.whoAmI = whoAmI;
	}

	public PersonalData getPersonalData() {
		return personalData;
	}

	public void setPersonalData(PersonalData personalData) {
		this.personalData = personalData;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
